package org.smart4j.chapter2.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.chapter2.util.PropsUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Administrator on 2015/11/26.
 */
public class DatabaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseHelper.class);

    private static final ThreadLocal<Connection> CONNECTION_HOLDER;

    private static final QueryRunner QUERY_RUNNER = new QueryRunner();

    private static final BasicDataSource DATA_SOURCE;

    static{
        CONNECTION_HOLDER = new ThreadLocal<Connection>();
        Properties conf = PropsUtil.loadProps("config.properties");
        String DRIVER = conf.getProperty("jdbc.driver");
        String URL = conf.getProperty("jdbc.url");
        String USERNAME = conf.getProperty("jdbc.username");
        String PASSWORD = conf.getProperty("jdbc.password");
        DATA_SOURCE = new BasicDataSource();
        DATA_SOURCE.setDriverClassName(DRIVER);
        DATA_SOURCE.setUrl(URL);
        DATA_SOURCE.setUsername(USERNAME);
        DATA_SOURCE.setPassword(PASSWORD);
    }

    public static Connection getConnection() {
        Connection conn = null;
        conn = CONNECTION_HOLDER.get();
        if(conn == null) {
            try {
                conn = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
        return conn;
    }

//    public static void closeConnection() {
//        Connection conn = CONNECTION_HOLDER.get();
//        if (conn != null) {
//            try {
//                conn.close();
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            } finally {
//                CONNECTION_HOLDER.remove();
//            }
//        }
//    }

    public static <T>List<T> queryEntityList(Class<T> entityClass,String sql, Object... params){
        List<T> entityList = null;
        Connection conn = null;
        try {
            conn = getConnection();
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return entityList;
    }

    public static List<Map<String, Object>> executeQuery(String sql, Object...params) {
        List<Map<String, Object>> result;
        try{
            Connection conn = getConnection();
            result = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static <T>  T queryEntity (Class<T> entityClass, String sql, Object...params) {
        T entity;
        try {
            Connection conn = getConnection();
            entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityClass), params);
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
        return entity;
    }

    public static int executeUpdate(String sql, Object... params) {
        int rows = 0;
        Connection conn = getConnection();
        try {
            rows = QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }
    public static <T> boolean insertEntity(Class<T> entityClass, Map<String, Object> fieldMap){
        if(fieldMap.isEmpty()) {
            return false;
        }
        String sql = "insert into" + getTableName(entityClass);
        StringBuilder columns = new StringBuilder("(");
        StringBuffer values = new StringBuffer("(");
        for(String fieldName : fieldMap.keySet()) {
            columns.append(fieldName).append(",");
            values.append("?,");
        }
        columns.replace(columns.lastIndexOf(","), columns.length(), ")");
        values.replace(values.lastIndexOf(","), values.length(), ")");
        sql += columns + "values" + values;
        Object[] params = fieldMap.values().toArray();
        return executeUpdate(sql, params) == 1;
    }
    public static String getTableName(Class<?> entityClass) {
        return entityClass.getSimpleName();
    }

    public static <T>boolean updateEntity(Class<T> entityClass, Map<String, Object> filedMap){
        if(filedMap.isEmpty()){
            return false;
        }
        String sql = "update " + getTableName(entityClass) + " set";
        StringBuilder columns = new StringBuilder("");
        for (String column : filedMap.keySet()){
            columns.append(column + "=?, ");
        }
        sql += columns.substring(0,columns.lastIndexOf(",")) + " where id = ?";
        List<Object> paramList = new ArrayList<Object>();
        paramList.addAll(filedMap.values());
        Object[] params = paramList.toArray();
        return executeUpdate(sql, params) == 1;
    }

    public static<T>boolean deleteEntity(Class<T> entityClass, int id) {
        String sql = "delete from" + getTableName(entityClass) + " where id = ?";
        return executeUpdate(sql, id) == 1;
    }
}

